package com.oahzuw;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Controller {

    @FXML
    private TextField urlTextFiled;

    @FXML
    private ListView fileListView;

    public static Map<String, String> map = new HashMap<>();

    public void checkFileList(MouseEvent mouseEvent) {
        map.clear();
        String text = urlTextFiled.getText();
        // 未指定目录
        if (!StringUtils.isNotBlank(text)) {
            showWarnMsg("警告信息！", "未指定Dota2回放目录，请指定！" +
                    "\n\t回放目录一般在Steam安装目录内：" +
                    "\nsteamapps\\common\\dota 2 beta\\game\\dota\\replays");
            return;
        }
        // 指定目录但未检索到dem回放文件
        File[] listFiles = new File(text).listFiles(pathname -> pathname.getAbsolutePath().endsWith(".dem") ? true : false);
        if (listFiles == null) {
            showWarnMsg("警告信息！", "指定目录非法！！！");
            return;
        }
        if (listFiles.length < 1) {
            showWarnMsg("警告信息！", "指定目录内，未发现Dota2回放文件！");
            return;
        }

        for (File file : listFiles) {
            map.put(file.getName(), file.getAbsolutePath());
        }

        ObservableList<String> files = FXCollections.observableArrayList(map.keySet());
        fileListView.setItems(files);
    }


    public void showWarnMsg(String title, String msg) {
        JOptionPane.showMessageDialog(null, msg, title, JOptionPane.WARNING_MESSAGE);
    }

    /**
     * 弹窗变量
     */
    Stage wxCode = new Stage();
    FlowPane pane = new FlowPane();
    Scene scene = new Scene(pane, 251, 251);
    Boolean isShow = false;
    Boolean isInit = false;

    private void wxCodeInit() {
        wxCode.setScene(scene);
        wxCode.setResizable(false);
        wxCode.setAlwaysOnTop(true);
        Image image = new Image(getClass().getResourceAsStream("qrcode.jpg"));
        ImageView imageView = new ImageView(image);
        pane.getChildren().add(imageView);
        // 指定 stage 的模式
        wxCode.setTitle("欢迎关注公众号！");
        wxCode.setOnCloseRequest((WindowEvent event) -> {
            isShow = false;
            wxCode.close();
        });
    }

    public void showWeiXinCode(MouseEvent mouseEvent) {
        if (!isShow) {
            isShow = true;
            if (!isInit) {
                isInit = true;
                wxCodeInit();
            }
            wxCode.showAndWait();
        }

    }
}
